var request = require('request');
var { result } = require('../lib/result');
var cheerio = require('cheerio');
var fs = require('fs');
var { home } = require('../conf.js');

//下载方法
var download = function(img, item){
    return new Promise( (reslove, reject) => {
        request.head(img.src, async function(err, res, body){
            if(err) {
                // reject(err);
                reslove({
                    src: '/assets/images/pic.jpg',
                    index: img.index
                });
            }else {
                let dir = home + '/upload/images';
                let filename = (+new Date()) + '.png';
                await request(img.src).pipe(fs.createWriteStream(dir + "/" + filename));
                let regx = new RegExp('@@img@@#' + img.index,'g');
                item.data = item.data.replace(regx, '/upload/images/' + filename);
                reslove({
                    src: filename,
                    index: img.index
                });
            }
        });
    });
};

function keyJudge(str) {
    let arr = ['webkit', 'linear'];
    let mark = false;
    arr.forEach(d => {
        if(str.indexOf(d) !== -1) {
            mark = true;
        }
    });
    if(!mark) {
        console.log(str + '\n\n')
    }
    return mark;
}

exports.spiderTpl = function(req, res) {
    // 图文
    // request(`http://www.135editor.com/style-center?cate_id=1&tag_id[]=151&tag_id[]=111&tag_id[]=222&page=${req.body.page}`, function (error, response, body) {
    
    // 分类
    request(`http://www.135editor.com/style-center?cate_id=1&tag_id=${req.body.tagid}&page=${req.body.page}`, function (error, response, body) {
    
    // 付费
    // request(`http://www.135editor.com/style-center?cate_id=1&only_paid=1&page=${req.body.page}`, function (error, response, body) {
    
    // 引导图
    // request(`http://www.135editor.com/style-center?cate_id=${req.body.tagid}&page=${req.body.page}`, function (error, response, body) {
        var $ = cheerio.load(body);
        var data = [];
        // console.log(body);

        // 引导图
        // $('.text-center').each(function() {
        
        // 其他的
        $('.editor-style-content').each(function() {
            let index = 0;
            let imgs = [];
            let $this = $(this);

            // 图片
            $this.find('img').each(function(){
                // 如果是懒加载
                let src = $(this).attr('src');
                if($(this).attr('data-src')) {
                    src = $(this).attr('data-src');
                }
                imgs.push({
                    index: index,
                    src: src
                });
                $(this).attr('src', `@@img@@#${index}`);
                index++;
            });
            // 背景
            $this.find('*').each(function(){
                let bg = $(this).css('background-image');
                let borderBg = $(this).css('-webkit-border-image');
                if(bg && !keyJudge(bg)) {
                    imgs.push({
                        index: index,
                        src: bg.replace(/url\((.+)\)/, '$1')
                    });
                    $(this).css('background-image', `url(@@img@@#${index})`);
                    index++;
                }
                if(borderBg && !keyJudge(borderBg)) {
                    imgs.push({
                        index: index,
                        src: borderBg.replace(/url\((.+)\)/, '$1')
                    });
                    $(this).css('-webkit-border-image', `url(@@img@@#${index})`);
                    index++;
                }
            });
            $this.find('[class]').removeAttr('class');
            let str = $this.html();
            data.push({
                name: $this.attr('data-name'),
                data: '<section class="RankEditor">' + str.replace(/(^\s*)|(\s*$)/g, "") + '</section>',
                imgs: imgs
            });
        })
        // 下载图片
        var arr = [];
        var imgs = [];
        data.forEach(item => {
            item.imgs.forEach( async d => {
                // 下载图片
                arr.push(await download(d, item));
            });
        });
        Promise.all(arr).then( resd => {
            console.log('??????????????', resd);
            result(req, res, {
                data: data
            });
        });
    });
}